<?php if(! defined('HAS_POWER') ) exit('无权访问!');
/**
==============================================================================
* Class RbacComponent GracePHP用户代理类组件
* @author 肖永标
* @date 2015-5-3
==============================================================================
*/

class RbacComponent extends Component {

    public function init()
    {
        if(Config::getItem('rbac.enable') === true)
        {
            $prefix = Config::getItem('db.tablePrefix');
            $userTable = Config::getItem('rbac.user_table_name');

            if(!$this->_hasTable($prefix . $userTable))
                throw new Exception('请先创建 ' . $prefix . $userTable . ' 表');

            if($this->_hasTable($prefix . 'role_' . $userTable) && $this->_hasTable($prefix . $userTable . '_access')
                && $this->_hasTable($prefix . $userTable . '_role') && $this->_hasTable($prefix . $userTable . '_role_access'))
            {
                return true;
            }

            $rbacSql = str_replace('<%tb%>', $userTable, file_get_contents(SYSTEM . '/data/rbac.sql'));

            $pdo = DB::getInstance();
            $pdo->query($rbacSql);
        }
        else
        {
            return false;
        }
    }

    /** 是否允许被加载
     * @return bool
     */
    public function allowLoad()
    {
        return true;
    }

    private function _hasTable($tableName)
    {
        $pdo = DB::getInstance();
        $query = $pdo->prepare("SHOW TABLES LIKE '" . $tableName . "'");
        $query->execute();
        $table = $query->fetchAll();

        return !empty($table);
    }
}